package com.hinnotek.amoeba.ui.activity.old

import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import com.google.gson.Gson
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.base.BaseBean
import com.hinnotek.amoeba.bean.old.*
import com.hinnotek.amoeba.databinding.ActivityPuachaseBinding
import com.hinnotek.amoeba.databinding.IncludePurchaseAddProductLayoutBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.utilities.ClickUtil
import com.lee.common.utils.SharedPreUtils
import com.hinnotek.amoeba.utilities.ToastUtils
import com.hinnotek.amoeba.ext.initAdapter
import com.hinnotek.amoeba.ext.productArray
import com.hinnotek.amoeba.viewmodels.AmibaCustomerViewModel
import com.hinnotek.amoeba.viewmodels.ManageViewModel
import com.hinnotek.amoeba.viewmodels.PublicInterfaceViewModel
import com.hinnotek.amoeba.widget.EditSpinnerC
import com.lee.common.network.getRequestBody
import com.lee.common.network.net.ObserverState
import com.xuexiang.xutil.common.StringUtils
import dagger.hilt.android.AndroidEntryPoint
import java.util.*

@AndroidEntryPoint
class PurchaseAddActivity : BaseActivity<ActivityPuachaseBinding>() {
    private var orgId = 0
    private var customerId = 0
    private var amibaCustomerProjectId = 0
    private var amibaProjectId = 0
    private var approvalUserId = 0


    private val viewModel by viewModels<PublicInterfaceViewModel>()
    private val manageViewModel by viewModels<ManageViewModel>()
    private val purchaseViewModel by viewModels<AmibaCustomerViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_puachase)
        setLeftVisible(true)
        setTitle("采购")

    }

    override fun initVew() {
        bindingView.rbAddProduct.setOnClickListener { v: View? ->
            val layoutBinding = DataBindingUtil.inflate<IncludePurchaseAddProductLayoutBinding>(
                layoutInflater,
                R.layout.include_purchase_add_product_layout,
                bindingView.llAddProduct,
                false
            )
            bindingView.llAddProduct.addView(layoutBinding.root)
            viewModel.getProductList()
                .observe(this, object : ObserverState<MutableList<ProductListBean>>() {
                    override fun onDataChange(data: MutableList<ProductListBean>) {
                        val strings = arrayOfNulls<String>(data.size).apply {
                            for (index in data.indices) {
                                this[index] = data[index].productName
                            }
                        }
                        layoutBinding.spinnerProductName.initAdapter(strings)
                        layoutBinding.spinnerProductName.setOnItemClickListener { parent, view, position, id ->
                            val bean = data[position]
                            val productTypePrice: String = bean.productPrice
                            layoutBinding.tvProductTypePrice.setText(productTypePrice)
                        }
                        super.onDataChange(data)
                    }

                    override fun onError(msg: String?, code: Int) {
                        super.onError(msg, code)
                    }
                })

            layoutBinding.tvDel.setOnClickListener { v1: View? ->
                bindingView.llAddProduct.removeView(
                    layoutBinding.root
                )
            }
        }

        bindingView.rbPurchasePd.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                bindingView.llChooseCustom.visibility = View.GONE
                bindingView.llChooseProject.visibility = View.GONE
                bindingView.llPdProject.visibility = View.VISIBLE
            } else {
                bindingView.llChooseCustom.visibility = View.VISIBLE
                bindingView.llChooseProject.visibility = View.VISIBLE
                bindingView.llPdProject.visibility = View.GONE
            }
        }
        bindingView.superButtonSubmit.setOnClickListener { v: View? ->
            if (ClickUtil.isFastClick()) {
                return@setOnClickListener
            }
            var escChooseCustomS = ""
            var escChooseProjectS = ""
            var provideProjectName = ""
            val companyPurchaseProjectJsonBean = CompanyPurchaseProjectJsonBean()
            val orgName = bindingView.escChooseAmb.editText.getText().toString().trim()
            if (StringUtils.isEmpty(orgName)) {
                ToastUtils.show(mContext, "请选择阿米巴")
                return@setOnClickListener
            }
            if (bindingView.rbPurchasePd.isChecked) {
                provideProjectName = bindingView.escPdChooseProject.editText.text.toString().trim()
                if (StringUtils.isEmpty(provideProjectName)) {
                    ToastUtils.show(mContext, "请选择项目")
                    return@setOnClickListener
                }
            } else {
                escChooseCustomS = bindingView.escChooseCustom.editText.text.toString().trim()
                if (StringUtils.isEmpty(escChooseCustomS)) {
                    ToastUtils.show(mContext, "请选择客户")
                    return@setOnClickListener
                }
                escChooseProjectS = bindingView.escChooseProject.editText.text.toString().trim()
                if (StringUtils.isEmpty(escChooseProjectS)) {
                    ToastUtils.show(mContext, "请选择项目")
                    return@setOnClickListener
                }
            }
            val escChooseNameS = bindingView.escChooseName.editText.text.toString().trim()
            if (StringUtils.isEmpty(escChooseNameS)) {
                ToastUtils.show(mContext, "请选择产品名称")
                return@setOnClickListener
            }
            val escChooseTypeS = bindingView.escChooseType.editText.text.toString().trim()
            if (StringUtils.isEmpty(escChooseTypeS)) {
                ToastUtils.show(mContext, "请选择产品型号")
                return@setOnClickListener
            }
            val tvProductTypePriceS = bindingView.tvProductTypePrice.text.toString().trim()
            val etPurchaseNumS = bindingView.etPurchaseNum.text.toString().trim()
            if (StringUtils.isEmpty(etPurchaseNumS)) {
                ToastUtils.show(mContext, "请填写采购数量")
                return@setOnClickListener
            }
            companyPurchaseProjectJsonBean.companyPurchaseProjects.add(
                CompanyPurchaseProjectJsonBean(
                    escChooseNameS,
                    escChooseTypeS,
                    tvProductTypePriceS,
                    etPurchaseNumS
                )
            )
            for (i in 0 until bindingView.llAddProduct.childCount) {
                val layout: View = bindingView.llAddProduct.getChildAt(i)
                val spinnerProductNameV: EditSpinnerC =
                    layout.findViewById(R.id.spinner_product_name)
                val spinnerProductTypeV: EditSpinnerC =
                    layout.findViewById(R.id.spinner_product_type)
                val tvProductTypePriceV: TextView = layout.findViewById(R.id.tv_product_type_price)
                val etPurchaseNumV: EditText = layout.findViewById(R.id.et_purchase_num)
                val spinnerProductNameVS = spinnerProductNameV.editText.text.toString().trim()
                if (StringUtils.isEmpty(spinnerProductNameVS)) {
                    ToastUtils.show(mContext, "请选择产品名称")
                    return@setOnClickListener
                }
                val spinnerProductTypeVS = spinnerProductTypeV.editText.text.toString().trim()
                if (StringUtils.isEmpty(spinnerProductTypeVS)) {
                    ToastUtils.show(mContext, "请选择规格型号")
                    return@setOnClickListener
                }
                val tvProductTypePriceVS = tvProductTypePriceV.text.toString()
                val etPurchaseNumVS = etPurchaseNumV.text.toString().trim()
                if (StringUtils.isEmpty(etPurchaseNumVS)) {
                    ToastUtils.show(mContext, "请填写采购数量")
                    return@setOnClickListener
                }
                companyPurchaseProjectJsonBean.companyPurchaseProjects.add(
                    CompanyPurchaseProjectJsonBean(
                        spinnerProductNameVS,
                        spinnerProductTypeVS,
                        tvProductTypePriceVS,
                        etPurchaseNumVS
                    )
                )
            }
            val etCostS = bindingView.etCost.text.toString().trim()
            val approvalUser = bindingView.escPurchaseApprover.editText.getText().toString().trim()
            if (StringUtils.isEmpty(approvalUser)) {
                ToastUtils.show(mContext, "请选择关联审批人")
                return@setOnClickListener
            }
            val projectRequirementsJson = Gson().toJson(companyPurchaseProjectJsonBean)
            addCompanyPurchase(
                orgId,
                orgName,
                customerId,
                escChooseCustomS,
                amibaCustomerProjectId,
                escChooseProjectS,
                amibaProjectId,
                provideProjectName,
                etCostS,
                approvalUserId,
                approvalUser,
                2,
                "宁创",
                projectRequirementsJson
            )
        }
    }

    override fun setData() {
        viewModel.getProductList()
            .observe(this, object : ObserverState<MutableList<ProductListBean>>() {
                override fun onDataChange(data: MutableList<ProductListBean>) {
                    var productId = 0
                    bindingView.escChooseName.initAdapter(productArray(data))
                    bindingView.escChooseName.setOnItemClickListener { parent, view, position, id ->
                        productId = data[position].productId
                    }
                    viewModel.getProductTypeListByProductId(productId)
                        .observe(this@PurchaseAddActivity,
                            object : ObserverState<MutableList<ProductManagamentBean>>() {
                                override fun onDataChange(data: MutableList<ProductManagamentBean>) {
                                    val strings = arrayOfNulls<String>(data.size).apply {
                                        for (index in data.indices) {
                                            this[index] = data[index].productTypeName
                                        }
                                    }
                                    bindingView.escChooseName.initAdapter(strings)
                                    bindingView.escChooseName.setOnItemClickListener { parent, view, position, id ->
                                        val bean = data[position]
                                        val productTypePrice: String = bean.productPrice
                                        bindingView.tvProductTypePrice.setText(productTypePrice)
                                    }
                                    super.onDataChange(data)
                                }
                            })
                    super.onDataChange(data)
                }
            })

        viewModel.getCompanySysUserAdmin()
            .observe(this, object : ObserverState<MutableList<AmibaSysUserAdminBean>>() {
                override fun onDataChange(data: MutableList<AmibaSysUserAdminBean>) {
                    val strings = arrayOfNulls<String>(data.size).apply {
                        for (index in data.indices) {
                            this[index] = data[index].personName
                        }
                    }
                    bindingView.escPurchaseApprover.initAdapter(strings)
                    bindingView.escChooseName.setOnItemClickListener { parent, view, position, id ->
                        approvalUserId = data[position].userId
                    }
                    super.onDataChange(data)
                }
            })
        getSysOrgAmibaList()
    }

    /**
     * app端添加商务采购接口
     */
    fun addCompanyPurchase(
        orgId: Int, orgName: String, customerId: Int, customerName: String,
        amibaCustomerProjectId: Int, projectName: String, amibaProjectId: Int,
        provideProjectName: String, purchaseMoney: String, approvalUserId: Int,
        approvalUser: String, sendUserId: Int, sendUser: String, amibaPurchaseProjectJson: String
    ) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()

        val map = mutableMapOf<String, Any>().apply {
            put("companyPurchaseType", if (bindingView.rbPurchasePd.isChecked) 1 else 2)
            put("applyUserId", SharedPreUtils.getInteger("userId", 0))
            put("orgId", orgId)
            put("orgName", orgName)
            if (bindingView.rbPurchasePd.isChecked) {
                put("amibaProjectId", amibaProjectId)
                put("provideProjectName", provideProjectName)
            } else {
                put("customerId", customerId)
                put("customerName", customerName)
                put("amibaCustomerProjectId", amibaCustomerProjectId)
                put("projectName", projectName)
            }
            put("purchaseMoney", purchaseMoney)
            put("approvalUserId", approvalUserId)
            put("approvalUser", approvalUser)
            put("sendUserId", sendUserId)
            put("sendUser", sendUser)
            put("companyPurchaseProjectJson", amibaPurchaseProjectJson)
            put("createUser", SharedPreUtils.getString("personName"))
        }

        purchaseViewModel.addCompanyPurchase(getRequestBody(map))
            .observe(this, object : ObserverState<BaseBean>() {
                override fun onDataChange(data: BaseBean) {
                    customDialog.dismiss()
                    finishActivity()
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    customDialog.dismiss()
                    ToastUtils.showShort(mContext, msg)
                    super.onError(msg, code)
                }
            })
    }

    /**
     * app端获取全部阿米巴组织接口
     */
    private fun getSysOrgAmibaList() {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()
        manageViewModel.getSysOrgAmibaList()
            .observe(this, object : ObserverState<MutableList<AmountAllocatedBean>>() {
                override fun onDataChange(data: MutableList<AmountAllocatedBean>) {
                    val strings = arrayOfNulls<String>(data.size)
                    for (index in data.indices) {
                        strings[index] = data[index].orgName
                    }
                    bindingView.escChooseAmb.initAdapter(strings)
                    bindingView.escChooseAmb.setOnItemClickListener { _, view, position, id ->
                        orgId = data[position].orgId
                        bindingView.escPdChooseProject.setText("")
                        bindingView.escChooseCustom.setText("")
                        viewModel.getAmibaProjectListByOrgId(orgId)
                            .observe(this@PurchaseAddActivity,
                                object : ObserverState<MutableList<AmibaProjectListBean>>() {
                                    override fun onDataChange(data: MutableList<AmibaProjectListBean>) {
                                        val arrayOfStrings = arrayOfNulls<String>(data.size)
                                        for (index in data.indices) {
                                            arrayOfStrings[index] = data[index].projectName
                                        }
                                        bindingView.escPdChooseProject.initAdapter(arrayOfStrings)
                                        bindingView.escPdChooseProject.setOnItemClickListener { parent, view, position, id ->
                                            amibaProjectId = data[position].amibaProjectId
                                        }
                                        super.onDataChange(data)
                                    }
                                })
                        viewModel.getAmibaCustomerListByOrgId(orgId)
                            .observe(this@PurchaseAddActivity,
                                object : ObserverState<MutableList<AmeobaCustomerListBean>>() {
                                    override fun onDataChange(data: MutableList<AmeobaCustomerListBean>) {
                                        val arrayOfStrings = arrayOfNulls<String>(data.size)
                                        for (index in data.indices) {
                                            arrayOfStrings[index] = data[index].customerName
                                        }
                                        bindingView.escChooseCustom.initAdapter(arrayOfStrings)
                                        val strings2 = arrayOfNulls<String>(0)
                                        bindingView.escChooseProject.initAdapter(strings2)
                                        bindingView.escChooseCustom.setOnItemClickListener { parent, view, position, id ->
                                            customerId = data[position].customerId
                                        }
                                        viewModel.getProjectByCustomerId(customerId)
                                            .observe(this@PurchaseAddActivity,
                                                object :
                                                    ObserverState<MutableList<ProjectByCustomerBean>>() {
                                                    override fun onDataChange(data: MutableList<ProjectByCustomerBean>) {
                                                        val strings21 =
                                                            arrayOfNulls<String>(data.size)
                                                        for (index in data.indices) {
                                                            arrayOfStrings[index] =
                                                                data[index].projectName
                                                        }
                                                        bindingView.escChooseProject.initAdapter(
                                                            strings21
                                                        )
                                                        bindingView.escChooseProject.setOnItemClickListener { _, _, position, id ->
                                                            amibaCustomerProjectId =
                                                                data[position].amibaCustomerProjectId
                                                        }
                                                        super.onDataChange(data)
                                                    }
                                                })

                                        super.onDataChange(data)
                                    }
                                })
                    }
                    super.onDataChange(data)
                }
            })
    }
}